<script setup lang="ts">
import { ref } from 'vue'
import { gatewayStore } from '@/store/gateway';
const gateway_store = gatewayStore()

const showCmdCenter = ref(false)
const contextMenuVisible = ref(false)
const isWebSocketPaused = ref(false)
const isManuallyPaused = ref(false)
const contextMenuStyle = ref({})
const isAutoPaused = ref(false)
import { WebsocketIo } from '@/utils/websocket';
const wsInstance = ref<WebsocketIo | null>(null)
wsInstance.value = WebsocketIo.getInstance;

// 指令中心发送指令方法
async function sendCmd(cmd: string) {
  return new Promise<string>((resolve) => {
    if (!wsInstance.value || !wsInstance.value.websocketIsNormal()) {
      return resolve('WebSocket 未连接');
    }
    const responses: any[] = [];
    let timeoutId: any;
    
    const handler = (event: CustomEvent) => {
      const data = event.detail;
      console.log('CmdFab: 收到WebSocket消息', data);
      
      // 检查是否是网关指令响应
      if (data.action === 'gatewayCommandResponse' || 
          (data.action === 'gateway_result' && data.type)) {
        console.log('CmdFab: 匹配到指令响应', data);
        responses.push(data);
        // 每次收到响应都重置超时，保证能收集连续响应
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          window.removeEventListener('websocket-message', handler as EventListener);
          resolve(JSON.stringify(responses));
        }, 1500); // 1.5秒内无新响应则判定收集完毕
      }
    };
    
    // 监听全局WebSocket消息事件
    window.addEventListener('websocket-message', handler as EventListener);
    wsInstance.value.sendMessage(cmd);
    
    // 最长等待5秒
    timeoutId = setTimeout(() => {
      window.removeEventListener('websocket-message', handler as EventListener);
      resolve(JSON.stringify(responses.length ? responses : '等待响应超时'));
    }, 5000);
  });
}
// 暂停/继续 WebSocket
const toggleWebSocketPause = () => {
  isManuallyPaused.value = !isManuallyPaused.value
  updatePauseState()
  hideContextMenu()
}
function showContextMenu(e: MouseEvent) {
  e.preventDefault()
  contextMenuVisible.value = true
  contextMenuStyle.value = {
    position: 'fixed',
    left: e.clientX + 'px',
    top: e.clientY + 'px',
    zIndex: 9999
  }
  document.addEventListener('click', hideContextMenu)
}
function hideContextMenu() {
  contextMenuVisible.value = false
  document.removeEventListener('click', hideContextMenu)
}
// 统一的暂停状态管理
const updatePauseState = () => {
  isWebSocketPaused.value = isManuallyPaused.value || isAutoPaused.value
}
</script>
<template>
    <!-- 悬浮指令中心按钮 -->
    <div class="fab-cmd-center" @click="showCmdCenter = true" title="快捷指令中心" v-if="gateway_store.debug">
      <el-icon style="font-size: 24px;">
        <Operation />
      </el-icon>
    </div>
    <!-- 指令中心弹窗 -->
    <cmd-center
      v-model="showCmdCenter"
      :send-cmd="sendCmd"
      :is-paused="isWebSocketPaused"
      :current-gateway-id="activeGatewayId"
      @toggle-pause="toggleWebSocketPause"
      @update:current-gateway-id="handleGatewaySwitch"
    />
      <teleport to="body">
    <div
      v-if="contextMenuVisible"
      :style="contextMenuStyle"
      class="my-context-menu"
    >
      <div @click="toggleWebSocketPause">
        {{ isManuallyPaused ? '恢复接收' : '暂停接收' }}
      </div>
    </div>

  </teleport>
</template>